#include<mpi.h>
#include<stdio.h>

int main(int argc, char*  argv[]) {
    int rank, size;

    MPI_Init(&argc, &argv);

    MPI_Status status;
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    int    bsize;      // 需要的缓冲空间大小
    int    sendn = 4;  // 发送的数据量
    void*  buffer;
    float  data[sendn] = {0};

    if (rank == 0) {
        data[0] = 1.0f;  data[1] = 2.0f; data[2] = 3.0f; data[3] = 4.0f;
        printf("\rank0 = %d\n", rank);

        //! 计算发送sendn个float需要的缓冲空间大小
        MPI_Pack_size(sendn, MPI_FLOAT, MPI_COMM_WORLD, &bsize);  
        buffer = malloc(bsize + MPI_BSEND_OVERHEAD);              // 申请缓存空间
        MPI_Buffer_attach(buffer, bsize + MPI_BSEND_OVERHEAD);    // 将缓存空间交给MPI纳管
        
        MPI_Bsend(&data, sendn, MPI_FLOAT, 1, 2000, MPI_COMM_WORLD);
        MPI_Buffer_detach(buffer, &bsize);                        // 解除与MPI的绑定
    } else if (rank == 1) {
        MPI_Recv(data, sendn, MPI_FLOAT, 0, 2000, MPI_COMM_WORLD, &status);
        printf("rank = %d, data = [%.2f, %.2f, %.2f, %.2f]\n", rank, data[0], data[1], data[2], data[3]);
    }

    MPI_Finalize();
    return 0;
}